package com.ca.demo.common.utils;

import java.io.*;

/**
 * @Author XieLei
 * @Date 2017/6/26 16:54
 */
public class FileUtil {

    public static String readFromFile(String path) {
        return readFromFile(path, "utf-8");
    }

    public static String readFromFile(String path, String encoding) {
        File file = new File(path);
        String lineSeparator = System.getProperty("line.separator");

        BufferedReader input = null;
        try {
            input = new BufferedReader(
                    new InputStreamReader(new FileInputStream(file), encoding));

            StringBuffer stringBuffer = new StringBuffer();
            String line = input.readLine();

            if (line != null && line.length() > 0 && line.charAt(0) == 0xfeff) {
                line = line.substring(1);
            }
            while (line != null) {
                stringBuffer.append(line);
                stringBuffer.append(lineSeparator);
                line = input.readLine();
            }
            return stringBuffer.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        return null;
    }
}
